// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import Antd from 'ant-design-vue'
import store from './store'
// import 'ant-design-vue/dist/antd.css'
import 'ant-design-vue/dist/antd.less'
import '@/assets/css/common.css'
import '@/assets/css/style.css'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import Base64 from 'js-base64'
import components from '@/components'
import directives from '@/directives'
import filters from '@/filters'
import validators from '@/utils/validators'
import storage from '@/utils/storage'
import VideoPlayer from 'vue-video-player/src'
import 'vue-video-player/src/custom-theme.css'
import 'video.js/dist/video-js.css'
import echarts from "echarts";
Vue.prototype.$echarts = echarts;

Vue.use(VideoPlayer)

// svg
import '@/icons'

import {
  componentsMap,
  constantRouteArr,
  staticRouteArr
} from '@/router/routerData.js'
import {Modal} from 'ant-design-vue'
import {list2MenuTree, list2treePerm} from "./utils/func";
import {qryAllPermByRoleIdAndUserCode} from "./api/system/permission";
import { whiteList } from '@/config'
// JSON格式化显示
import JsonViewer from 'vue-json-viewer'
import { tokenValid } from './api/sso'
import { getLoginUrl } from './api/portalSetting'
import { appConfig } from './config/app'
import {qryUserRefDetail} from "@/api/login";
import { getSetting } from '@/api/system/permission'
import {checkFileIsIllegal} from '@/utils/ant_handler'
import { iniWeb } from '@/utils/func.js';

Vue.use(JsonViewer)
Vue.prototype.$eventHub = Vue.prototype.$eventHub || new Vue()
Vue.prototype.$checkFileIsIllegal = checkFileIsIllegal

/**
 * 非开发环境 不打印console.log
 * @type {(function(): void)|*}
 */
console.log = (function (myConsole) {
  return function () {
    if (process.env.NODE_ENV === 'development')
      myConsole(...arguments)
  }
})(console.log)

Vue.config.productionTip = false
Vue.use(Base64)
Vue.use(components)
Vue.use(directives)
Vue.use(filters)
Vue.use(Antd)
Vue.use(validators)

NProgress.configure({ showSpinner: false }) // NProgress Configuration

// 全局mixin，用于表单中的响应式排版配置，主要用于col的属性，v-bind="colConfig"
Vue.mixin({
  data() {
    return {
      colConfig: { xxl: 6, xl: 8, lg: 12, sm: 24 },
      formCol: { lg: 12, sm: 24 }
    }
  },
  computed: {
    hasPerm() {
      return function (permCode) {
        return this.$store.state.permCodes[permCode] !== undefined
      }
    }
  },
  methods: {

    toPortal () {
      location.href = location.origin + '/sjsc/'
    },
    async toGldPath(url) {
      // if(!appConfig[url]){
      //   let res = await getLoginUrl()
      //   let { purLoginUrl, portalUrl } = res.data || {};
      //   appConfig.loginUrl = purLoginUrl
      //   appConfig.portalUrl = portalUrl
      // }
      // window.location.href = appConfig[url];
      if(!storage.session.get('isLogin') ) {
        let orUrl = undefined
        if (window.location.origin.indexOf('pre') != -1) {
          orUrl = encodeURI('https://ygscpre.szexgrp.com')
        } else if (window.location.origin.indexOf('test') != -1) {
          orUrl = encodeURI('https://ygsctest.szexgrp.com')
        } else {
          orUrl = encodeURI('https://ygsc.szexgrp.com')
        }
        //判断重定向地址跳转商城或供应商
        // let returnUrl = orUrl +  (type == 'ygcg'?'%2F%23%2FcallbackSso%3FuserToken%3D%24%7BuserToken%7D%26jumpType%3Dygcg':'%2F%23%2FcallbackSso%3FuserToken%3D%24%7BuserToken%7D%26jumpType%3Dgys')
        let returnUrl = orUrl + this.escapeUrl('/#/callbackSso?userToken=${userToken}&jumpType=ygcg')
        console.log('重定向路径', returnUrl);
        // let url2 = `https://tradetest.szggzy.com/ggzy/center/#/login?redirect=${returnUrl}&target=outside`


        // window.open(url2, '_self', 'noopener=yes,noreferrer=yes')
      }else {
        console.log('000000000000',appConfig)

         if(!appConfig[url]){
        let res = await getLoginUrl()
        let { purLoginUrl, portalUrl } = res.data || {};
        appConfig.loginUrl = purLoginUrl
        appConfig.portalUrl = portalUrl
      }
      // window.location.href = appConfig[url];
      }


    },
    escapeUrl(url) {
      let escUrl = encodeURIComponent(url);
      return escUrl
  },
  }
})

router.beforeEach((to, from, next) => {
  NProgress.start() // start progress bar
  // const gldToken = storage.session.get('gldToken')
  // if (gldToken) {
  //   tokenValid({ userToken: gldToken }).then(res => {
  //     if (res.code !== 0) {
  //       // token无效 刷新登录状态
  //       removeAll()
  //     }
  //     next()
  //   }).catch(e => {
  //     console.log(e)
  //     next()
  //   })
  // }
  const authToken = storage.session.get('authToken')
  const userInfo = storage.session.get('userInfo')

  if(authToken&&!userInfo){
    // getInfo(to,from,next)

  } else {
    // getSettingInfo()
    next()
  }
  // if (storage.session.get('authToken')) {
  //   // 判断是否有token
  //   if (!store.state.isLogin) {
  //     store.commit('setIsLogin', true)
  //     loadDynamicRouter(to, next)
  //     next({...to, replace: true})
  //   } else {
  //     next()
  //   }
  // } else {
  //   if (whiteList.indexOf(to.path) !== -1) {
  //     // 在免登录白名单，直接进入
  //     next()
  //   } else {
  //     next('/login') // 否则全部重定向到登录页
  //   }
  // }
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})

// eslint-disable-next-line no-new
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})
function getInfo(to,from,next){
  qryUserRefDetail().then(res => {
      if(res.code == 0) {
        res.data.userInfo.deptInfo = res.data.deptInfo
      storage.session.set('userInfo', res.data.userInfo)
        loadDynamicRouter()
      next({...to, replace: true });

      }
  })
}
function getSettingInfo(to,from,next){
  getSetting().then(res => {
      if(res.code == 0) {
        // res.data.userInfo.deptInfo = res.data.deptInfo
      storage.session.set('portalSettingsInfo', res.data)
        iniWeb()
        // loadDynamicRouter()
      // next({...to, replace: true });

      }
  })
}
function removeAll() {
  storage.session.remove('isLogin')
  storage.session.remove('authToken')
  storage.session.remove('userInfo')
  storage.session.remove('portalSettingsInfo')
  storage.session.remove('topPermTree')
  storage.session.remove('role')
  storage.session.remove('roles')
  storage.session.remove('gldToken')
  storage.session.remove('wallet')
}
function loadDynamicRouter(to, next) {
  let components = componentsMap
  let menuArr = []
  let routeArr = []
  let roleCode = storage.session.get('role')
  const roles = storage.session.get('roles')
  if (!roleCode && roles && roles.length > 0) {
    roleCode = roles[0]
  }
  constantRouteArr.forEach(item =>
    routeArr.push({
      ...item,
      name: item.id,
      path: '/' + item.id,
      component: () => import(`@/views/${components[item.id]}`)
    })
  )
  console.log('routeArr',routeArr)
  // 系统管理员 菜单配置、角色权限
  if (roleCode === 'SYSTEM_ADMIN') {
    staticRouteArr.forEach(item =>
      routeArr.push({
        ...item,
        name: item.id,
        path: '/' + item.id,
        component: () => import(`@/views/${components[item.id]}`)
      })
    )
  }

  if (roleCode) {
    let params = {
      roleId: roleCode
    };
    qryAllPermByRoleIdAndUserCode(params).then(response => {
      if (response.code === 0) {
        response.data = response.data.filter(item => !item.module)
        const permData = response.data.length > 0 ? response.data.filter(item => item.isCheck) : []
        store.commit('setUserPerm', permData)

        const permTree = list2MenuTree(response.data, 'permId', 'pPermId', 'permName')
        let tempMenuList = permTree.filter(item => item.children && item.children.length > 0 ? item.children.filter(child => child.isCheck).length > 0 : item.isCheck)
        let menuList = []
        tempMenuList.forEach(item => {
          if (item.children && item.children.length > 0) {
            const temp = item
            temp.children = temp.children.filter(t => t.isCheck && t.permType === '1')
            menuList.push(temp)
          } else {
            menuList.push(item)
          }
        })
        menuList.sort((a, b) => a.orderNum - b.orderNum)
        appConfig.menuList = menuList
        menuList && menuList.length > 0 && store.commit('setCurrentMenu', menuList[0].id)
        for (let item of permData) {
          let { permName, permId, pPermId, url } = item
          if (url && url.length > 0) {
            const newRoute = {
              id: url,
              pId: item.pUrl,
              path: "/" + url,
              component: resolve => require([`@/views/${components[url]}`], resolve),
              name: item.routeName,
              meta: {permName, permId, pPermId}  // 用于自动构建面包屑时使用
            }
            routeArr.unshift(newRoute);
          }
        }
        menuArr = list2route(routeArr, "id", "pId")
        menuArr.push({path: '*', redirect: {name: 'notFound'}})
        router.addRoutes(menuArr)
        next({...to, replace: true})
      } else {
        menuArr.push({path: '*', redirect: {name: 'notFound'}})
        router.addRoutes(menuArr)
        next({...to, replace: true})
      }
    });
  } else {
    menuArr.push({path: '*', redirect: {name: 'notFound'}})
    router.addRoutes(menuArr)

    return Modal.error({
      content: '未开通交易权限，返回首页',
      onOk() {
        window.location.replace(`${window.location.origin}/sjsc/#/`)
      }
    })

    next({...to, replace: true})
  }
}
/*function loadDynamicRouter() {
  let components = componentsMap
  let routeArr = []
  constantRouteArr.forEach(item =>
    routeArr.push({
      ...item,
      name: item.id,
      path: '/' + item.id,
      component: () => import(`@/views/${components[item.id]}`)
    })
  )
  let tree = list2route(routeArr, 'id', 'pId')
  tree.push({ path: '*', redirect: { name: 'notFound' } })
  router.addRoutes(tree)
}*/

function list2route(data, id, pid) {
  let d
  let o
  let t = {}
  for (let i in data) {
    d = data[i]
    if (t[d[id]] && t[d[id]].id) continue
    o = {
      id: d[id],
      pid: d[pid],
      path: d['path'],
      component: d['component'],
      name: d['name'],
      meta: d['meta'] || {},
      data: d
    }
    if (d.children) {
      o.children = d.children
      delete d.children
    }
    if (o.pid) {
      if (!t[o.pid]) {
        t[o.pid] = { children: [o] }
      } else if (!t[o.pid].children) {
        t[o.pid].children = [o]
      } else {
        t[o.pid].children.push(o)
      }
    }
    if (t[o.id]) {
      o.children = o.children
        ? o.children.concat(t[o.id].children)
        : t[o.id].children
    }
    t[o.id] = o
  }
  let tree = []
  for (let i in t) {
    if (!t[i].data) {
      tree = tree.concat(t[i].children)
    } else if (!t[i].data[pid]) tree.push(t[i])
  }
  return tree
}
